package com.example.cinema.drawview;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PointF;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.example.cinema.R;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.ExecutionException;

import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

import static android.view.MotionEvent.ACTION_DOWN;
import static android.view.MotionEvent.ACTION_UP;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

public class LivePlayerVideo extends FrameLayout {



    public LivePlayerVideo(Context context) {
        this(context, null);
    }

    public LivePlayerVideo(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    private Context context;
    private TypedArray typedArray;
    private String playurl;

    public LivePlayerVideo(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        typedArray = context.obtainStyledAttributes(attrs, R.styleable.PlayerVideo, defStyleAttr, 0);
        playurl = typedArray.getString(R.styleable.PlayerVideo_playurl);
        this.context = context;
        init();
    }

    long doentime = 0;
    long uptime = 0;
    boolean isdblClick = false;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int ev = event.getActionMasked();
        boolean isdown = true;
        if (ev == ACTION_DOWN) {
            ChildAdd(event.getX(), event.getY());
        }

        return true;
    }

    //添加星星
    private int width;
    private int heigh;

    private void ChildAdd(float x, float y) {
        Log.i("PPP", x + "");
        Log.i("PPP", y + "");
        width = getMeasuredWidth();
        heigh = getMeasuredHeight();
        Random random = new Random();
        ImageView img = new ImageView(context);
        img.setImageDrawable(getResources().getDrawable(R.mipmap.love));

        LayoutParams params = new LayoutParams(MATCH_PARENT, MATCH_PARENT);
        params.leftMargin = width / 2 - 75;
        params.topMargin = heigh - 75;
        params.width = 150;
        params.height = 150;
        img.setLayoutParams(params);


        img.setColorFilter(Color.argb( random.nextInt(255), random.nextInt(255), random.nextInt(255), 1));
        addView(img);
        Animations(img);
    }

    //动画
    private void Animations(View view) {
        int w = width / 4;
        int h = heigh / 4;
        Random random = new Random();


        PointF pointFstart = new PointF();
        pointFstart.x = width / 2;
        pointFstart.y = heigh;


        PointF pointF0 = new PointF();
        pointF0.x = random.nextInt(width / 4);
        pointF0.y = heigh / 3 * 2;


        PointF pointF1 = new PointF();
        pointF0.x = random.nextInt(width);
        pointF0.y = heigh / 3;


        PointF pointFend = new PointF();
        pointFend.x = width / 2;
        pointFend.y = 0;


        Bazier bazier = new Bazier(pointF0, pointF1);
        ValueAnimator animator = ValueAnimator.ofObject(bazier, pointFstart, pointFend);
        animator.setDuration(3000);
        animator.setInterpolator(new LinearInterpolator());
        animator.start();
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                PointF pointF = (PointF) animation.getAnimatedValue();
                view.setX(pointF.x);
                view.setY(pointF.y);
                view.setAlpha(1 - animation.getAnimatedFraction());
                if (animation.getAnimatedFraction() >= 1) {
                    removeView(view);
                }
            }
        });

    }


    private IjkMediaPlayer mediaPlayer;
    private SurfaceView surfaceView;

    private void init() {
        surfaceView = new SurfaceView(context);//创建图形绘制SurfaceView
        surfaceView.getHolder().addCallback(new CallbackListener());//图形绘制添加回调
        //创建布局参数设置宽高
        LayoutParams params = new LayoutParams(MATCH_PARENT, MATCH_PARENT);
        surfaceView.setLayoutParams(params);
        addView(surfaceView);//将图形绘制添加到重叠布局中
    }

    //外部设置Url
    public void setPlayurl(String playurl) {
        this.playurl = playurl;
        Log.i("UUUU", "接收到传值" + playurl);
    }

    //封面等绘制
    private String coverurl;
    private ImageView coverimg;
    private ImageView statrimg;
    private ImageView loading;

    public void setImgUrl(String imgUrl) {
        coverurl = imgUrl;
        if (coverimg == null) {
            coverimg = new ImageView(context);
            coverimg.setScaleType(ImageView.ScaleType.FIT_XY);
            Glide.with(coverimg).load(imgUrl).into(coverimg);
            addView(coverimg);
        }
        if (statrimg == null) {
            statrimg = new ImageView(context);
            statrimg.setImageDrawable(getResources().getDrawable(R.drawable.player_btn_state));
            LayoutParams params = new LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
            params.width = 100;
            params.height = 100;
            params.gravity = Gravity.CENTER;
            statrimg.setLayoutParams(params);
            addView(statrimg);
            statrimg.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    new ImgAsty().execute();
                    if(mediaPlayer!=null)
                    {
                        mediaPlayer.start();
                        statrimg.setVisibility(GONE);
                    }else {
                        loadVideo();
                        statrimg.setVisibility(GONE);
                    }

                }
            });
        }

        if (loading == null) {
            loading = new ImageView(context);
            loading.setImageDrawable(getResources().getDrawable(R.mipmap.ch));
            LayoutParams paramss = new LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
            paramss.width = 100;
            paramss.height = 100;
            paramss.gravity = Gravity.CENTER;
            loading.setLayoutParams(paramss);
            loading.setVisibility(GONE);
            addView(loading);
        }


    }

    //模糊
    class ImgAsty extends AsyncTask<Void, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(Void... voids) {
            Bitmap bitmap = null;
            try {
                bitmap = imagevague();
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            Glide.with(coverimg).load(bitmap).into(coverimg);
        }
    }

    Allocation inpallocation;
    Allocation outallocation;

    private Bitmap imagevague() throws ExecutionException, InterruptedException {
        Bitmap b = Glide.with(coverimg).asBitmap().load(coverurl).submit().get();
        //创建一个空的Bitmap
        //创建一个空的Bitmap用于输出
        Bitmap outbitmap = Bitmap.createBitmap(b.getWidth(), b.getHeight(), Bitmap.Config.ARGB_8888);
        //初始化RenderScript工具类
        RenderScript script = RenderScript.create(context);
        //创建高斯模糊对象
        ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(script, Element.U8_4(script));
        //为RenderScript分配内存空间
        inpallocation = Allocation.createFromBitmap(script, b);//输入内存
        outallocation = Allocation.createFromBitmap(script, outbitmap);//输出内存
        //设置渲染的模糊属性
        blur.setRadius(20);
        //设置渲染后的输入内存
        blur.setInput(inpallocation);
        //输出数据到输出内存中
        blur.forEach(outallocation);
        //讲数据填充到空的输出bitmap中
        outallocation.copyTo(outbitmap);
        blur.destroy();//销毁
        return outbitmap;
    }

    //开始继续播放
    public void Playstart() {
        if (mediaPlayer != null) {


            coverimg.setVisibility(GONE);
            if(statrimg!=null)
            {
                statrimg.setVisibility(GONE);
            }

            loading.setVisibility(GONE);
            mediaPlayer.start();
            mediaPlayer.setDisplay(surfaceView.getHolder());

            thread = new Thread(new FrameListener());

        }
    }

    //暂停
    public void Playstop() {
        if (mediaPlayer != null) {
            isthread = false;
            if(mediaPlayer.isPlaying())
            {
                mediaPlayer.pause();
            }
            statrimg.setVisibility(VISIBLE);
            Log.i("PPPP","停止完成");
        }
        Log.i("PPPP","停止、走完");
    }

    //释放
    public void Playrelease() {
        if (mediaPlayer != null) {
            isthread = false;
//            mediaPlayer.stop();
            mediaPlayer.release();
//            coverimg.setVisibility(VISIBLE);
//            statrimg.setVisibility(VISIBLE);
        }
    }

    //第一次播放
    private int h;
    private int w;
    private long progress;

    public void loadVideo() {
        if (mediaPlayer != null) {
            mediaPlayer.release();
        }
        mediaPlayer = new IjkMediaPlayer();
        try {
            mediaPlayer.setDataSource(playurl);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mediaPlayer.setDisplay(surfaceView.getHolder());
        mediaPlayer.prepareAsync();
        //播放器信息侦听
        mediaPlayer.setOnInfoListener(new IMediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(IMediaPlayer iMediaPlayer, int i, int i1) {
                Log.i("bbbb",i+"");
                Log.i("bbbb",i1+"");
                if (mediaPlayer != null) {
                    Log.i("PPPS","刷新画面");
                    mediaPlayer.setDisplay(surfaceView.getHolder());
                }
                return false;
            }
        });
        //准备准听器
        mediaPlayer.setOnPreparedListener(new IMediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(IMediaPlayer iMediaPlayer) {
                coverimg.setVisibility(GONE);
                width = getMeasuredWidth();
                heigh = getMeasuredHeight();



                int pw = context.getResources().getDisplayMetrics().widthPixels;
                int ph =  context.getResources().getDisplayMetrics().heightPixels;
                Log.i("JJJ", "高度1:" + heigh);
                int videowidth = iMediaPlayer.getVideoWidth();
                int videoheigh = iMediaPlayer.getVideoHeight();
                Log.i("JJJ", "宽度" + videowidth);
                Log.i("JJJ", "高度" + videoheigh);

                if(videowidth>videoheigh)
                {
                    int ss = width/16*9;
                    h = ss;
                    w = width;
                    Log.i("JJJ", "w宽度" + w);
                    Log.i("JJJ", "h高度" + h);
                }else {
                    int mm = width*16/9;
                    h = mm;
                    w = width;
                    Log.i("JJJ", "w宽度" + w);
                    Log.i("JJJ", "h高度" + h);
                }
                Log.i("JJJ", "w宽度" + w);
                Log.i("JJJ", "h高度" + h);


                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT);
                params.height = h;
                params.width = w;

                params.gravity = Gravity.CENTER;
                Log.i("RRRR", h + "");
                Log.i("RRRR", h + "");
                surfaceView.setLayoutParams(params);
                mediaPlayer.setDisplay(surfaceView.getHolder());

            }
        });
        //帧监听
        mediaPlayer.setOnBufferingUpdateListener(new IMediaPlayer.OnBufferingUpdateListener() {
            @Override
            public void onBufferingUpdate(IMediaPlayer iMediaPlayer, int i) {
                mediaPlayer.setDisplay(surfaceView.getHolder());
                Log.i("JJJ","帧播放");
            }
        });
        //状态消息
        mediaPlayer.setOnCompletionListener(new IMediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(IMediaPlayer iMediaPlayer) {
                Log.i("AAAA", "状态");
            }
        });
        //控制器事件
        mediaPlayer.setOnControlMessageListener(new IjkMediaPlayer.OnControlMessageListener() {
            @Override
            public String onControlResolveSegmentUrl(int i) {
                Log.i("CCC", i + "");
                return null;
            }
        });
        //播放错误
        mediaPlayer.setOnErrorListener(new IMediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(IMediaPlayer iMediaPlayer, int i, int i1) {
                if(LiveError!=null)
                {
                    LiveError.onError();
                }
                return false;
            }
        });
        new ImgAsty().execute();
        if(statrimg!=null)
        {
            statrimg.setVisibility(GONE);
        }


        thread = new Thread(new FrameListener());
        thread.start();
    }

    //缓冲监听
    private Thread thread;
    private boolean isthread = true;

    class FrameListener implements Runnable {
        @Override
        public void run() {
            while (isthread) {
                Message message = new Message();
                handler.sendMessage(message);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            long p = mediaPlayer.getCurrentPosition();
            if (p <= progress) {
                loading.setVisibility(VISIBLE);
                progress = p;
                loading.animate().rotationBy(360)
                        .setInterpolator(new LinearInterpolator())
                        .setDuration(1000).start();
                if(onloadingListener != null)
                {
                    onloadingListener.loading();
                }
            } else {
                loading.setVisibility(GONE);
            }

        }
    };
    //缓冲外调接口
    public interface OnloadingListener{
        void loading();
    }
    private OnloadingListener onloadingListener;
    public void setOnLoadingListener(OnloadingListener loadingListener)
    {
        onloadingListener = loadingListener;
    }
    //播放错误外调
    public interface OnLiveEErrorListener{
        void onError();
    }
    public OnLiveEErrorListener LiveError;
    public void SetOnErrorListener(OnLiveEErrorListener error)
    {
        LiveError = error;
    }
    /****************************图形处理监听*************************/
    class CallbackListener implements SurfaceHolder.Callback {
        @Override
        public void surfaceCreated(@NonNull SurfaceHolder holder) {
            Log.i("JJJ","绘制创建");
        }

        @Override
        public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
            Log.i("JJJ","绘制中");
            mediaPlayer.setDisplay(surfaceView.getHolder());
        }

        @Override
        public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
            Log.i("JJJ","绘制销毁");
        }
    }

}
